/**
 * @author Peter
 *
 */

package security.channel;

import java.io.IOException;
import java.net.Socket;

import org.bouncycastle.util.encoders.Base64;

public class Base64Channel extends TCPChannel {

	public Base64Channel(Socket socket) throws IOException {
		super(socket);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.channel.TCPChannel#println(java.lang.String)
	 */
	@Override
	public void println(String message) {
		super.println(new String(Base64.encode(message.getBytes())));
	}

	/**
	 * Encodes that message-bytes with base64 and then print it with a
	 * tcp-channel.
	 * 
	 * @param message
	 *            the message-bytes to send.
	 */
	protected void printlnBytes(byte[] message) {
		//System.out.println("vor base64:" + message); // TODO delete
		byte[] base64Encoded = Base64.encode(message);
		String base64EncodedString = new String(base64Encoded);
		//System.out.println("nach base64:" + base64EncodedString); // TODO delete

		super.println(base64EncodedString);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.channel.TCPChannel#readLine()
	 */
	@Override
	public String readLine() throws IOException {
		return new String(Base64.decode(super.readLine().getBytes()));
	}

	/**
	 * Reads a string from an tcp-channel an decodes it. If the string was null
	 * or '!list' then don't decode it and just pass this string.
	 * 
	 * @return the base64 decoded bytes.
	 * @throws IOException
	 *             if any IOException occurs.
	 */
	protected byte[] readLineBytes() throws IOException {
		String message = super.readLine();
		if (message == null) { // if socket receives null do not decode
			return null;
		}
		if (message.equals("!list") || message.equals("!end") || message.startsWith("!notok")) {
			return message.getBytes();
		}

		//System.out.println("mit base64 erhalten:" + message); // TODO delete
		byte[] base64Decoded = Base64.decode(message.getBytes());
		//System.out.println("mit base64 entschluesselt:" + base64Decoded); // TODO
																			// delete
		return base64Decoded;
	}
}